package cog.support.springmvc.model;

import cog.support.util.common.StringKit;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 分页基础操作类
 * @author 陈杰
 * @since 20160919
 * @version v1.0
 *
 * Copyright ChenJie(chenjie_java@aliyun.com) 2016年8月11日 01:23:55
 */
public class PageCondition {

    private String page;

    private int pageNumber;

    private int pageSize;

    public PageCondition(){
        if(getReqeust()) this.getCokiePageSize("pageSize","50");
    }

    private void initParameters(String str) {
        if (StringKit.isNotEmpty(str)) {
            String[] param = str.split("_");
            if (param.length > 0) {
                this.pageNumber = Integer.parseInt(param[0]);
            }
            if (param.length > 1) {
                this.pageSize = Integer.parseInt(param[1]);
            }
        }
    }

    /**
     * 创建COOKIE 存储每页显示条数
     * @param name
     * @param value
     */
    private void getCokiePageSize(String name,String value){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();;
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(30 * 24 * 60 * 60);   //存活期为一个月 30*24*60*60
        cookie.setPath("/");
        response.addCookie(cookie);
        this.pageSize = Integer.parseInt(cookie.getValue());
    }

    /**
     * 得到COOKIE
     * @return
     */
    private boolean getReqeust() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        for(Cookie cookie :request.getCookies()){
            if(cookie.getName().equals("pageSize")){
                this.pageSize = Integer.parseInt(cookie.getValue());
                return false;
            }
        }
        return true;
    }

    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
        this.initParameters(page);
    }

    public int getPageNumber() {
        return pageNumber;
    }

    public void setPageNumber(int pageNumber) {
        this.pageNumber = pageNumber;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    /**
     * 判段page是否为空
     *
     * @return boolean 是否为空
     */
    public boolean isNotEmpty() {
        return page != null && page.length() > 0;
    }

}